<template>
  <!-- el国际化设置 -->
  <el-config-provider :locale="zhCn">
    <div>
      <LoginViewVue v-if="!isLogin" />
    </div>
    <div class="index-view">
      <el-container>
        <el-header>
          <div class="header">
            <div class="logo_layout">
              <img src="@/assets/logo.jpeg" />
              <span>翠微旅居</span>
            </div>
            <el-menu :default-active="curSecondMenu" mode="horizontal">
              <el-menu-item v-for="(item, index) in getMenuList" :key="index" :index="item.key">
                <div class="menu" @click="navRoute(item)">
                  <el-icon>
                    <component :is="item.icon" />
                  </el-icon>
                  {{ item.title }}
                </div>
              </el-menu-item>
            </el-menu>
            <div class="user-info">
              <div>{{ userInfo.name }}</div>
              <div>{{ userInfo.roleName }}</div>
              <div>{{ userInfo.shopName }}</div>
            </div>
            <el-dropdown>
              <span class="el-dropdown-link">
                <el-image :src="userInfo.avatar" fit="fill">
                  <template #error>
                    <div class="image-slot">
                      <el-icon :size="20">
                        <User />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
                <el-icon :size="20">
                  <CaretBottom />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openPassword">修改密码</el-dropdown-item>
                  <el-dropdown-item @click="logOut">退出</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-container>
          <el-aside width="170px" v-show="curSecondMenu != 'overview'">
            <NavMenu :data="secondMenu" />
          </el-aside>
          <el-main>
            <router-view />
          </el-main>
        </el-container>
      </el-container>
      <el-dialog v-model="dialogVisible" title="修改密码" width="35%" top="30vh" class="base_dialog">
        <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
          <el-form-item label="旧密码" prop="old">
            <el-input v-model="passwordForm.old" type="password" show-password placeholder="请输入" />
          </el-form-item>
          <el-form-item label="新密码" prop="new">
            <el-input v-model="passwordForm.new" type="password" show-password placeholder="请输入" />
          </el-form-item>
          <el-form-item label="重复新密码" prop="repetition">
            <el-input v-model="passwordForm.repetition" type="password" show-password placeholder="请输入" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitForm(passwordFormRef)">保存</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup>
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import NavMenu from "@/components/NavMenu.vue";
import useRoute from "@util/router";
import { ref, reactive, computed, watch } from "vue";
import { CaretBottom, User } from "@element-plus/icons-vue";
import LoginViewVue from "@view/account/LoginView.vue";
import event from "@util/eventBus";
import auth from "@net/auth";
import api from "@api/accout";
import $ from "@util/base";
import useAccoutStore from "@store/accout"

const accoutStore = useAccoutStore()

const isLogin = ref(auth.getToken() == null ? false : true);
event.registerEvent("AUTH_FAIL", () => {
  isLogin.value = false;
});
event.registerEvent("LOGIN", () => {
  isLogin.value = true;
});

const userInfo = ref({
  avatar: null,
  name: null,
  permissionList: null,
});

if (isLogin.value) {
  getUserInfo();
}
var isFirst = true
function getUserInfo() {
  api.userInfo((val) => {
    userInfo.value = val;
    let isAll = val.permissionList.indexOf("cw-manage-overview-all") != -1;
    auth.setOverView(isAll, val.shopCode, val.shopName);
    let isCombo =
      val.permissionList.indexOf("cw-manage-order-travel-combo") != -1;
    let isMember =
      val.permissionList.indexOf("cw-manage-order-travel-member") != -1;
    auth.setTravelOrder(isCombo, isMember);
    // 1040002分店 1040001总店
    accoutStore.setUserInfo({
      mainStore: val.shopLevel === '1040001' ? true : false
    })

    if (isFirst) {
      isFirst = false
      setSecondMenu(curSecondMenu.value)
    }
  });
}

const menuList = [
  {
    title: "概览",
    key: "overview",
    route: "/overview",
    icon: "DataAnalysis",
    code: "cw-manage-overview",
  },
  {
    title: "商品",
    key: "goods",
    route: "/goodsinput",
    icon: "Goods",
    code: "cw-manage-goods",
  },
  {
    title: "旅行",
    key: "travel",
    route: "/travelinput",
    icon: "Location",
    code: "cw-manage-travel",
  },
  {
    title: "酒店",
    key: "hotel",
    route: "/hotelinput",
    icon: "OfficeBuilding",
    code: "cw-manage-hotel",
  },
  {
    title: "订单",
    key: "order",
    route: "/goodsorder",
    icon: "Van",
    code: "cw-manage-order",
  },
  {
    title: "营销",
    key: "marketing",
    route: "/promotionsmanager",
    icon: "Present",
    code: "cw-manage-market",
  },
  {
    title: "财务",
    key: "finance",
    route: "/transactiondetail",
    icon: "Wallet",
    code: "cw-manage-finance",
  },
  {
    title: "审批",
    key: "examine",
    route: "/goodsexamine",
    icon: "DocumentChecked",
    code: "cw-manage-approval",
  },
  {
    title: "会员",
    key: "member",
    route: "/membermanager",
    icon: "User",
    code: "cw-manage-member",
  },
  {
    title: "设置",
    key: "setting",
    route: "/companyinformation",
    icon: "Setting",
    code: "cw-manage-install",
  },
];

const getMenuList = computed(() => {
  let list = [];
  if (!$.isEmpty(userInfo.value.permissionList)) {
    list = menuList.filter((e) => {
      for (const key of userInfo.value.permissionList) {
        if (key.indexOf(e.code) != -1) {
          return true
        }
      }
      return false
      // console.log(e.code,userInfo.value.permissionList.indexOf(e.code))
      // return userInfo.value.permissionList.indexOf(e.code) != -1;
    });
  } else {
    list = menuList;
  }
  return list;
});

const goodsSecondMenu = [
  {
    title: "商品管理",
    code: "cw-manage-goods-manage",
    itemList: [
      {
        title: "商品录入",
        route: "/goodsinput",
        code: "cw-manage-goods-manage-add",
      },
      {
        title: "商品管理",
        route: "/goodsmanager",
        code: "cw-manage-goods-manage-list",
      },
      {
        title: "库存管理",
        route: "/stockmanager",
        code: "cw-manage-goods-manage-stocklist",
      },
      {
        title: "库存变更记录",
        route: "/stockrecode",
        code: "cw-manage-goods-manage-stockchangelist",
      },
    ],
  },
  {
    title: "商品配置",
    code: "cw-manage-goods-config",
    itemList: [
      {
        title: "规格管理",
        route: "/specsmanager",
        code: "cw-manage-goods-config-specs",
      },
      {
        title: "商品标签管理",
        route: "/goodslabelmanager",
        code: "cw-manage-goods-config-label",
      },
      {
        title: "邮费模板管理",
        route: "/expressmanager",
        code: "cw-manage-goods-config-postagetemplate",
      },
      {
        title: "自提点管理",
        route: "/takegoodsmanager",
        code: "cw-manage-goods-config-sep",
      },
    ],
  },
];

const travelSecondMenu = [
  {
    title: "旅行管理",
    code: "cw-manage-travel-manage",
    itemList: [
      {
        title: "产品录入",
        route: "/travelinput",
        code: "cw-manage-travel-manage-add",
      },
      {
        title: "产品管理",
        route: "/travelmanager",
        code: "cw-manage-travel-manage-list",
      },
      {
        title: "团期余位管理",
        route: "/groupremainmanager",
        code: "cw-manage-travel-manage-group-remainSeat",
      },
    ],
  },
  {
    title: "旅行配置",
    code: "cw-manage-travel-config",
    itemList: [
      {
        title: "产品属性管理",
        route: "/travellabelmanager",
        code: "cw-manage-travel-config-productlabel",
      },
      {
        title: "产品内容管理",
        route: "/groupmanager",
        code: "cw-manage-travel-config-joinnature",
      },
      {
        title: '附加费用管理',
        route: '/additionalfeesmanager',
        code: "cw-manage-travel-config-additional-fees",
      },
      {
        title: '产品分类管理',
        route: '/travelclassifymanager',
        code: "cw-manage-travel-config-classify",
      }
    ],
  },
];

const hotelSecondMenu = [
  {
    title: "酒店管理",
    code: "cw-manage-hotel-manage",
    itemList: [
      {
        title: "酒店录入",
        route: "/hotelinput",
        code: "cw-manage-hotel-manage-add",
      },
      {
        title: "酒店管理",
        route: "/hotelmanager",
        code: "cw-manage-hotel-manage-list",
      },
      {
        title: "库存管理",
        route: "/hotelstockmanager",
        code: "cw-manage-hotel-stock-control",
      },
    ],
  },
  {
    title: "酒店配置",
    code: "cw-manage-hotel-config",
    itemList: [
      {
        title: "酒店设施管理",
        route: "/hotelfacilitiemanager",
        code: "cw-manage-hotel-config-plan",
      },
      {
        title: "房间设施管理",
        route: "/roomfacilitiemanager",
        code: "cw-manage-hotel-config-rooms",
      },
      {
        title: "餐饮服务管理",
        route: "/servicemanager",
        code: "cw-manage-hotel-config-cateringservice",
      },
    ],
  },
];

const orderSecondMenu = [
  {
    title: "订单管理",
    code: "cw-manage-order",
    itemList: [
      {
        title: "商品订单",
        route: "/goodsorder",
        code: "cw-manage-order-product",
      },
      {
        title: "旅行订单",
        route: "/travelorder",
        code: "cw-manage-order-travel-member",
      },
      {
        title: "酒店订单",
        route: "/hotelorder",
        code: "cw-manage-order-travel-hotel",
      },
      {
        title: "售后订单",
        route: "/aftersaleorder",
        code: "cw-manage-order-after-sale",
      },
    ],
  },
];

const marketingSecondMenu = [
  {
    title: "优惠活动",
    code: "cw-manage-market-activity",
    itemList: [
      {
        title: "优惠活动管理",
        route: "/promotionsmanager",
        code: "cw-manage-market-activity-list",
      },
      {
        title: "礼包管理",
        route: "/giftmanager",
        code: "cw-manage-market-activity-giftbag",
      },
    ],
  },
  {
    title: "优惠券",
    code: "cw-manage-market-coupon",
    itemList: [
      {
        title: "优惠券管理",
        route: "/couponmanager",
        code: "cw-manage-market-coupon-list",
      },
    ],
  },
  {
    title: "推荐管理",
    code: "cw-manage-market-recommend",
    itemList: [
      {
        title: "首页Banner图",
        route: "/bannerconfigure",
        code: "cw-manage-market-recommend-homebanner",
      },
      {
        title: "首页热门推荐",
        route: "/recommendconfigure",
        code: "cw-manage-market-recommend-hot",
      },
    ],
  },
  {
    title: "短信营销",
    code: "cw-manage-market-message",
    itemList: [
      {
        title: "短信营销管理",
        route: "/messagemanage",
        code: "cw-manage-market-message-list",
      }
    ],
  },
];

const financeSecondMenu = [
  {
    title: "财务管理",
    code: "cw-manage-finance",
    itemList: [
      {
        title: "结算中心",
        route: "/transactiondetail",
        code: "cw-manage-finance-transactiondetails",
      },
      {
        title: "储值管理",
        route: "/depositmanager",
        code: "cw-manage-finance-stored-value",
      },
      {
        title: "积分管理",
        route: "/pointsmanager",
        code: "cw-manage-finance-stored-value",
      },
      {
        title: "库存管理",
        route: "/financestockmanager",
        code: "cw-manage-finance-transactiondetails",
      },
      {
        title: "出纳管理",
        route: "/cashiermanager",
        code: "cw-manage-finance-transactiondetails",
      },
      {
        title: "发票管理",
        route: "/invoicemanager",
        code: "cw-manage-finance-transactiondetails",
      },
      {
        title: "合同管理",
        route: "/contractmanager",
        code: "cw-manage-finance-transactiondetails",
      },
      {
        title: "基地管理",
        route: "/basemanager2",
        code: "cw-manage-finance-transactiondetails",
      }
    ],
  }
];

const examineSecondMenu = [
  {
    title: "审批中心",
    code: "cw-manage-approval",
    itemList: [
      {
        title: "商品审批",
        route: "/goodsexamine",
        code: "cw-manage-approval-product",
      },
      {
        title: "旅行审批",
        route: "/travelexamine",
        code: "cw-manage-approval-travel",
      },
      {
        title: "酒店审批",
        route: "/hotelexamine",
        code: "cw-manage-approval-hotel",
      },
      {
        title: "储值审批",
        route: "/depositexamine",
        code: "cw-manage-approval-deposit",
      },
      {
        title: "积分审批",
        route: "/pointsexamine",
        code: "cw-manage-approval-deposit",
      },
    ],
  },
];

const memberSecondMenu = [
  {
    title: "会员管理",
    code: "cw-manage-member",
    itemList: [
      {
        title: "会员管理",
        route: "/membermanager",
        code: "cw-manage-member-list",
      },
      {
        title: "分销员管理",
        route: "/distributormanager",
        code: "cw-manage-member-distributorshiplist",
      },
    ],
  },
];

const settingSecondMenu = [
  {
    title: "系统设置",
    code: "cw-manage-install",
    itemList: [
      {
        title: "公司信息",
        route: "/companyinformation",
        code: "cw-manage-install-company",
      },
      {
        title: "基地管理",
        route: "/basemanager",
        code: "cw-manage-install-shop",
      },
      {
        title: "用户管理",
        route: "/usermanager",
        code: "cw-manage-install-account",
      },
      {
        title: "角色管理",
        route: "/rolemanager",
        code: "cw-manage-install-role",
      },
    ],
  },
];

const curSecondMenu = ref("overview");

const secondMenu = ref([])

function setSecondMenu(value) {
  let list = [];
  switch (value) {
    case "overview":
      list = [];
      break;
    case "goods":
      list = goodsSecondMenu;
      break;
    case "travel":
      list = travelSecondMenu;
      break;
    case "hotel":
      list = hotelSecondMenu;
      break;
    case "order":
      list = orderSecondMenu;
      break;
    case "marketing":
      list = marketingSecondMenu;
      break;
    case "finance":
      list = financeSecondMenu;
      break;
    case "examine":
      list = examineSecondMenu;
      break;
    case "member":
      list = memberSecondMenu;
      break;
    case "setting":
      list = settingSecondMenu;
      break;
    default:
      list = [];
  }
  if (!$.isEmpty(userInfo.value.permissionList)) {
    // list = list.filter((e) => {
    //   return userInfo.value.permissionList.indexOf(e.code) != -1;
    // });
    // list = list.filter((e) => {
    //   for (const key of userInfo.value.permissionList) {
    //     if (key.indexOf(e.code) != -1) {
    //       return true
    //     }
    //   }
    //   return false
    // })

    for (let i = list.length - 1; i >= 0; i--) {
      const parent = list[i];
      var parentExist = false
      for (const permission of userInfo.value.permissionList) {
        if (permission.indexOf(parent.code) != -1) {
          parentExist = true
          break
        }
      }
      if (!parentExist) {
        list.splice(i, 1)
      } else {
        parent.itemList = parent.itemList.filter(val=>{
          return userInfo.value.permissionList.indexOf(val.code) != -1
        })
        // const child = parent.itemList
        // parent.itemList = child.filter(val => {
        //   if (val.title == "旅行订单") {
        //     if (userInfo.value.permissionList.indexOf(val.code[0]) == -1) {
        //       val.route = "/travelorder";
        //     } else {
        //       val.route = "/travelgrouporder";
        //     }
        //     return (
        //       userInfo.value.permissionList.indexOf(val.code[0]) != -1 ||
        //       userInfo.value.permissionList.indexOf(val.code[1]) != -1
        //     );
        //   } else {
        //     return userInfo.value.permissionList.indexOf(val.code) != -1
        //   }
        // })


        // console.log(userInfo.value.permissionList)
        // for (let j = child.length - 1; j >= 0; j--) {
        //   var childExist = false
        //   const childElement = child[j];
        //   for (const permission of userInfo.value.permissionList) {
        //     if (childElement.code.indexOf(permission) != -1) {
        //       childExist = true
        //       break
        //     }
        //   }
        //   if (!childExist) {
        //     child.splice(j, 1)
        //   }
        // }
      }
    }
    // list.forEach((item) => {
    //   item.itemList = item.itemList.filter((e) => {
    //     if (e.title == "旅行订单") {
    //       if (userInfo.value.permissionList.indexOf(e.code[0]) == -1) {
    //         e.route = "/travelorder";
    //       } else {
    //         e.route = "/travelgrouporder";
    //       }
    //       return (
    //         userInfo.value.permissionList.indexOf(e.code[0]) != -1 ||
    //         userInfo.value.permissionList.indexOf(e.code[1]) != -1
    //       );
    //     } else {
    //       return userInfo.value.permissionList.indexOf(e.code) != -1;
    //     }
    //   });
    // });
  }
  if (list.length > 0) {
    route.push(list[0].itemList[0].route)
  }
  secondMenu.value = list
}

function navRoute(item) {
  if (item.key == "overview") {
    route.push(menuList[0].route)
  } else {
    setSecondMenu(item.key)
  }
}

const route = useRoute();
route.watchRouter(null, (route) => {
  let name = route.meta.activeMainMenu;
  if (name != null && name != undefined && name != curSecondMenu.value) {
    curSecondMenu.value = name;
  }
});

const dialogVisible = ref(false);
const passwordFormRef = ref("");
const passwordForm = reactive({
  old: "",
  new: "",
  repetition: "",
});

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入重复新密码"));
  } else if (value !== passwordForm.new) {
    callback(new Error("两次输入不匹配!"));
  } else {
    callback();
  }
};

const passwordRules = {
  old: [
    {
      required: true,
      message: "请输入旧密码",
      trigger: "blur",
    },
  ],
  new: [
    {
      required: true,
      message: "请输入新密码",
      trigger: "blur",
    },
  ],
  repetition: [
    {
      required: true,
      validator: validatePass2,
      trigger: "blur",
    },
  ],
};

function openPassword() {
  dialogVisible.value = true;
}

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      changePassword();
    } else {
      console.log("error submit!", fields);
    }
  });
};

function changePassword() {
  api.changePassword(
    {
      oldPassword: passwordForm.old,
      newPassword: passwordForm.new,
    },
    (val) => {
      logOut();
    }
  );
}

function logOut() {
  api.logout((val) => {
    auth.removeToken();
    location.reload();
  });
}
</script>
<style lang="scss">
.index-view {
  .el-header {
    --el-header-padding: 0;
  }

  .header {
    width: 100%;
    display: flex;
    align-items: center;
    border-bottom: solid 1px var(--el-menu-border-color);

    .logo_layout {
      display: flex;
      align-items: center;
      margin-right: 20px;

      img {
        width: 40px;
        height: 40px;
        margin-left: 10px;
        margin-right: 6px;
      }

      span {
        font-weight: 500;
        font-size: 18px;
        color: #333;
      }
    }

    .logo {
      width: 170px;
      text-align: center;
    }

    .el-menu {
      width: calc(100% - 350px);
    }

    .el-menu--horizontal {
      border-bottom: none;
    }

    .el-menu-item {
      padding: 0;
    }

    .menu {
      display: flex;
      align-items: center;
      padding: 0 10px 0 10px;
    }

    .el-menu-item [class^=el-icon] {
      margin-right: 0;
    }

    .user-info {
      width: 100px;
      font-size: 12px;
      color: #303133;
      text-align: right;
    }

    .el-dropdown-link {
      width: 80px;
      display: flex;
      align-items: center;
      justify-content: space-around;

      .el-image {
        width: 40px;
        height: 40px;

        img {
          border-radius: 50%;
        }
      }

      .el-image__wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .el-main {
    --el-main-padding: 0;
    height: calc(100vh - 60px);
  }

  // .el-menu {
  //   --el-menu-bg-color: #329FEB;
  //   --el-menu-text-color: #fff;
  //   --el-menu-active-color: #ffd04b;
  //   --el-menu-active-bg-color: #ffd04b;
  //   --el-menu-hover-text-color: #fff;
  //   --el-menu-hover-bg-color: rgb(40, 127, 188);
  //   --el-menu-level: 0;
  // }

  // a {
  //   text-decoration: none;
  // }
}

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  height: 100vh;
}

a {
  text-decoration: none;
}

body,
ul,
li {
  margin: 0;
}

ul,
li {
  padding: 0;
}

img {
  object-fit: cover;
}

.dashed_but {
  border: 2px dashed $primary;
  border-radius: 5px;
  line-height: 28px;
  padding: 10px;
  margin: 10px;
  text-align: center;
  cursor: pointer;
  color: #333;
}

.pointer {
  cursor: pointer;
}

.input_width {
  width: 140px;
}

.m_b_15 {
  margin-bottom: 15px;
}

.m_b_10 {
  margin-bottom: 10px;
}

.drawer_date_picker {

  .el-date-editor.el-input,
  .el-date-editor.el-input__wrapper {
    width: 300px !important;
  }
}
</style>
